package com.dean.service.impl;

import com.dean.entity.DeanResponse;
import com.dean.exception.DeanRuntimeException;
import com.dean.service.support.AbstractDeanScriptService;
import com.dean.utils.FileUtils;
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DeanGroovyService
 * @Description groovy 脚本服务 带class的脚本不支持
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class DeanGroovyService  extends AbstractDeanScriptService {
    private static final GroovyScriptEngineFactory scriptEngineFactory = new GroovyScriptEngineFactory();

    @Override
    public DeanResponse call(String script, Map<String, Object> parameters) {
        ScriptEngine scriptEngine = scriptEngineFactory.getScriptEngine();
        try {
            scriptEngine.eval(script);
            Invocable invocable = (Invocable) scriptEngine;
            Map<String,Object> params = init();
            params.putAll(parameters);
            Object res =  invocable.invokeFunction("call",params);
            return DeanResponse.ok(res);
        } catch (javax.script.ScriptException | NoSuchMethodException e) {
            DeanRuntimeException.throwException(996,e.getMessage(),e);
        }
        return DeanResponse.ok();
    }

//    public static void main(String[] args) throws IOException {
//        DeanGroovyService groovyService = new DeanGroovyService();
//        Map<String,Object> params =  new HashMap<>();
//        System.out.println(DeanGroovyService.class.getClassLoader().getResource(""));
//        File file  = new File(DeanGroovyService.class.getClassLoader().getResource("").getPath()+"scripts/hello.groovy");
//        System.out.println(FileUtils.readFile(file.getPath()));
//        groovyService.call(file,params);
//        //groovyService.call("def call(Map<String,Object> params){println(params); return 1}",params);
//    }


}
